package org.afun.csms_android;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;

public class MusicPlayer extends AppCompatActivity {

    private MediaPlayer player;            //定义MediaPlayer对象
    private boolean isPause = false;        //定义是否暂停
    private boolean isPlay;
    private boolean isStop;

    private SeekBar seekBar;
    private TextView currentTV;
    private TextView totalTV;

    private ProgressThread progressThread;

    private Button btn;

    @SuppressLint("SdCardPath")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_player);
        //设置全屏显示
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        final ImageButton btn_play = (ImageButton) findViewById(R.id.btn_play); //获取“播放/暂停”按钮
        final ImageButton btn_stop = (ImageButton) findViewById(R.id.btn_stop); //获取“停止”按钮

        seekBar = findViewById(R.id.seekBar);
        currentTV = findViewById(R.id.currentTV);
        totalTV = findViewById(R.id.totalTV);
        btn = findViewById(R.id.button);


        //创建MediaPlayer对象,并解析要播放的音频文件
        player = MediaPlayer.create(this, R.raw.cyx);
//        Log.i("TEST",""+player.getCurrentPosition()/1000);
        currentTV.setText(calculateTime(player.getCurrentPosition() / 1000));
        totalTV.setText(calculateTime(player.getDuration() / 1000));


        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressThread.stopThread();
                finish();
            }
        });

        //为MediaPlayer添加完成事件监听器，实现当音频播放完毕后，重新开始播放音频
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                isStop = false;
                isPause = false;
                isPlay = true;
                seekBar.setProgress(0);
                player.seekTo(0);

                play();                               //调用play()方法，实现播放功能
            }
        });

        // 初始化进度条
        initProgress();

        // 开启线程跟踪
        progressThread = new ProgressThread();
        progressThread.start();


        btn_play.setOnClickListener(new View.OnClickListener() {  //实现继续播放与暂停播放
            @Override
            public void onClick(View v) {
                if (player.isPlaying() && !isPause) {         //如果音频处于播放状态
                    player.pause();                            //暂停播放
                    isPause = true;                           //设置为暂停状态
                    isPlay = false;
                    isStop = false;
                    //更换为播放图标
                    ((ImageButton) v).setImageDrawable(getResources().getDrawable(R.drawable.play, null));
                } else {
                    isStop = false;
                    isPause = false;
                    isPlay = true;
                    player.start();                           //继续播放
                    // 更换为暂停图标
                    ((ImageButton) v).setImageDrawable(getResources().getDrawable(R.drawable.pause, null));
                    isPause = false;                         //设置为播放状态
                }
            }
        });

        btn_stop.setOnClickListener(new View.OnClickListener() { //单击停止按钮，实现停止播放音频
            @Override
            public void onClick(View v) {
                isStop = true;
                isPause = false;
                isPlay = false;
                player.stop();                    //停止播放
                //更换为播放图标
                btn_play.setImageDrawable(getResources().getDrawable(R.drawable.play, null));
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    player.seekTo(progress);
                }
                currentTV.setText(calculateTime(player.getCurrentPosition() / 1000));
                totalTV.setText(calculateTime(player.getDuration() / 1000));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    private void play() {  //创建play()，实现音频播放功能
        try {
            player.reset();                                         //重置MediaPlayer对象
            player.prepare();                                       //预加载音频
            player.start();                                         //开始播放
            isStop = false;
            isPause = false;
            isPlay = true;
        } catch (Exception e) {
            e.printStackTrace();                                    //输出异常信息
        }
    }

    @Override
    protected void onDestroy() {  //当前Activity销毁时,停止正在播放的音频,并释放MediaPlayer所占用的资源
        progressThread.stopThread();        // 关闭子线程
        if (player.isPlaying()) {             //如果音频处于播放状态
            player.stop();                    //停止音频的播放
            isStop = true;
            isPause = false;
            isPlay = false;
        }
        player.release();                    //释放资源
        super.onDestroy();
    }


    private void initProgress() {
        seekBar.setMax(player.getDuration());

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                currentTV.setText(calculateTime(player.getCurrentPosition()));
                player.seekTo(seekBar.getProgress());
            }
        });
    }

    class ProgressThread extends Thread {
        boolean flag = true;

        @Override
        public void run() {
            super.run();
            while (flag) {
                if (player.isPlaying()) {
                    seekBar.setProgress(player.getCurrentPosition());
                }
            }
        }

        public void stopThread() {
            this.flag = false;
        }
    }

    //计算播放时间
    public String calculateTime(int time) {
        int minute;
        int second;
        if (time > 60) {
            minute = time / 60;
            second = time % 60;
            //分钟再0~9
            if (minute >= 0 && minute < 10) {
                //判断秒
                if (second >= 0 && second < 10) {
                    return "0" + minute + ":" + "0" + second;
                } else {
                    return "0" + minute + ":" + second;
                }
            } else {
                //分钟大于10再判断秒
                if (second >= 0 && second < 10) {
                    return minute + ":" + "0" + second;
                } else {
                    return minute + ":" + second;
                }
            }
        } else if (time < 60) {
            second = time;
            if (second >= 0 && second < 10) {
                return "00:" + "0" + second;
            } else {
                return "00:" + second;
            }
        }
        return null;
    }
}